/*******************************************************************************
 * Developer: Ian Doyle
 * Date:      6/23/2012
 *
 * All code Copyright (C) 2012 Ian Doyle. All rights reserved.
 *
 * This file is a part of FileFocus.
 *
 * FileFocus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * FileFocus is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with FileFocus.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/


package filefocus;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.TreeMap;

import filefocus.exception.FailedExecutionException;
import filefocus.exception.UnreadableFileException;

public class FileSizeFileDigestDoubleMap extends
		TreeMap<Long, GrowableTreeBranch<FileDigestMap>> implements FileOrganizationTreeBranch {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8747876911094862745L;
	
	private int numFiles;
	private FileType fType;
	private FileSizeReader fSizer;
	
	public FileSizeFileDigestDoubleMap(FileType fileType)
	{
		numFiles = 0;
		fType = fileType;
		fSizer = FileFocusProcessors.fileSizeReader(fType);
	}

	@Override
	public void addFile(File file) throws NoSuchAlgorithmException, FileNotFoundException, IOException, UnreadableFileException, FailedExecutionException, InterruptedException {
		Long fileLength = new Long(fSizer.getFileSize(file));
		GrowableTreeBranch<FileDigestMap> map = get(fileLength);
		if(map == null)
		{
			map = new GrowableTreeBranch<FileDigestMap>(new FileDigestMap(fType));
			map.addFile(file);
			put(fileLength, map);
		}
		else
		{
			map.addFile(file);
		}
		++numFiles;
	}

	@Override
	public int count() {
		return numFiles;
	}

	@Override
	public Collection<FileList> flatten() {
		ArrayList<FileList> list = new ArrayList<FileList>();
		for(Iterator<GrowableTreeBranch<FileDigestMap>> i = values().iterator(); i.hasNext(); list.addAll(i.next().flatten()));
		return list;
	}

}
